package com.test.encprytool;

import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 将要加密/解密的内容放在default文件中，放入cooler项目根目录中，
 * 修改main中的调用函数，如要加密，使用encryptOffsetByte，解密使用encryptPffsetByte
 * 运行后，会在根目录生成result.txt，文件内容既为加密/解密结果
 */
public class EncryptTool {

    public static void main(String args[]) {
        String rawData = readFile("default.json");
        JsonParser parser = new JsonParser();
        JsonElement obj = parser.parse(rawData);
        rawData = obj.toString();

        String result = encryptOffsetByte(rawData);
        writeFile("default", result);
    }

    public static void writeFile(String path, String data) {
        File file = new File(path);
        BufferedOutputStream bos = null;
        try {
            bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(data.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                }
            }
        }
    }

    public static String readFile(String path) {
        File file = new File(path);
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[4096];
            int readLen = -1;
            while ((readLen = bis.read(buffer)) > 0) {
                bos.write(buffer, 0, readLen);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                }
            }
        }

        return bos.toString();
    }


    public static String encryptOffsetByte(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); ++i) {
            sb.append((char) (str.charAt(i) + 3));
        }
        return sb.toString();
    }

    public static String decryptOffsetByte(String str) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < str.length(); ++i) {
            sb.append((char) (str.charAt(i) - 3));
        }
        return sb.toString();
    }
}

